/**
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.sebastianqu.common.widget;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import com.example.android.Demo.R;

/**
 * @author qu sheng
 *
 */
public class TimeButton extends Button {

    private static String TAG = TimeButton.class.getSimpleName();
    private static String STRING_FORMAT = "hhmm";
    private static String DEFAULT_FORMAT = "hh:mm";
    private Date mDate;
    private String format;

    public TimeButton(Context context) {
        super(context);
        initMembers();
    }

    public TimeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initMembers();
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.TimeButton);

        String format = ta.getString(R.styleable.TimeButton_timeFormat);
        String value = ta.getString(R.styleable.TimeButton_timeValue);
        //System.out.println(value);
        setFormat(format);
        setValue(value);
        ta.recycle();
    }

    public TimeButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Log.d(TAG, "DateButton(Context context, AttributeSet attrs, int defStyle)");
        initMembers();
    }

    /**
     *
     * @return
     */
    public String getDataString() {
        Log.d(TAG, "getDataString");
        SimpleDateFormat df = new SimpleDateFormat(STRING_FORMAT);
        if (null == this.mDate) {
            return df.format(new Date());
        }
        return df.format(this.mDate);
    }

    /**
     * 返回日期
     *
     * @return 日期
     */
    public Date getValue() {
        Log.d(TAG, "getValue");
        return this.mDate;
    }

    /**
     * the date to set
     *
     * @param date
     */
    public void setValue(String date) {
        Log.d(TAG, "setValue");
        try {
        if (null != date && !"".equals(date))
            this.mDate = new Date(date);
        } catch (IllegalArgumentException ex) {
            if (isInEditMode())
                this.mDate = new Date();
            else
                throw ex;
        }
        this.setText(null, null);
    }

    /**
     * 返回显示用的日期字符串
     *
     * @return 显示用的日期字符串
     */
    public String getViewString() {
        Log.d(TAG, "getViewString");
        SimpleDateFormat df;
        if (null == this.format || "".equals(this.format)) {
            if (!isInEditMode()) {
                df = (SimpleDateFormat) DateFormat.getTimeFormat(this.getContext());
            } else {
                df = new SimpleDateFormat(DEFAULT_FORMAT);
            }
        } else {
            df = new SimpleDateFormat(this.format);
        }
        if (this.isInEditMode() && null == this.mDate) {
            return df.format(new Date());
        }
        if (this.mDate == null)
            return df.format(new Date());
        return df.format(this.mDate);
    }

    /**
     * @see TextView
     */
    @Override
    public void setText(CharSequence text, BufferType type) {
        Log.d(TAG, "setText(" + text + ")");
        super.setText(getViewString(), type);
    }

    /**
     * @see TextView
     */
    @Override
    public String getText() {
        Log.d(TAG, "getText");
        return getDataString();
    }

    /**
     * @return the formate
     */
    public String getFormat() {
        Log.d(TAG, "getFormat");
        return format;
    }

    /**
     * @param formate
     *            the formate to set
     */
    public void setFormat(String format) {
        Log.d(TAG, "setFormat");
        if (null != format || !"".equals(format))
            this.format = format;
    }

// ----------------------- Private
    private void initMembers() {
        Log.d(TAG, "initMembers");
        this.mDate = new Date();
        this.format = ((SimpleDateFormat) DateFormat.getTimeFormat(this.getContext())).toPattern();
        if (!isInEditMode()) this.setOnClickListener(new TimeButtonOnClickListener());
    }

// ----------------------- Protected
    /**
     *
     */
    protected class TimeButtonOnClickListener implements OnClickListener {
        /**
         *
         */
        @Override
        public void onClick(View v) {
            if (!isInEditMode()) {
                TimePickerDialog dialog = new TimePickerDialog(v.getContext(),
                        new OnTimeSetListenerAtDateButton(), mDate.getHours(),
                        mDate.getMinutes(), DateFormat.is24HourFormat(v
                                .getContext()));
                dialog.show();
            }
        }
    }

    protected class OnTimeSetListenerAtDateButton implements TimePickerDialog.OnTimeSetListener {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mDate = new Date();
            mDate.setHours(hourOfDay);
            mDate.setMinutes(minute);

            setText(getViewString(), null);
        }

    }
}
